package com.xiebishe.mylibrary.net.retrofit.remoteCallAdapter

import com.xiebishe.mylibrary.net.retrofit.bean.NetBaseBean
import kotlinx.coroutines.CancellationException
import retrofit2.Call
import retrofit2.HttpException
import java.io.IOException
import java.net.SocketException

class RetrofitRemoteCall<T>(private val call: Call<NetBaseBean<T>>) : RemoteCall<T>() {

    @Volatile
    private var lastCall: Call<NetBaseBean<T>>? = null

    override fun cancel() {
        lastCall?.cancel()
    }

    override fun sync(): T {
        try {
            val realCall = call.clone()
            lastCall = realCall
            val res = realCall.execute()
            if (res.isSuccessful) {
                return res.body()!!.data
            } else {
                throw HttpException(res)
            }
        } catch (e: SocketException) {
            if (e.message == "Socket closed") {
                throw CancellationException()
            } else {
                throw e
            }

        } catch (e: IOException) {
            if (e.message == "Canceled") {
                throw CancellationException()
            } else {
                throw e
            }
        }


    }
}
